package com.example.commom.interceptor;


import com.example.commom.exception.CustomException;
import com.example.commom.redis.RedisUtils;
import com.example.commom.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class LoginInterceptorToken implements HandlerInterceptor {

    /**
     * 登陆前, 触发的方法.
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 打印请求信息
        log.info("------------- LoginInterceptor 开始 -------------");
        long startTime = System.currentTimeMillis();
        request.setAttribute("requestStartTime", startTime);

        // OPTIONS请求不做校验,
        // 前后端分离的架构, 前端会发一个OPTIONS请求先做预检, 对预检请求不做校验
        if(request.getMethod().toUpperCase().equals("OPTIONS")){
            return true;
        }

        String path = request.getRequestURL().toString();
        log.info("接口登录拦截: path：{}", path);

        //获取header的token参数
        String token = request.getHeader("token");
        log.info("登录校验开始, token: {}", token);
        if (token == null || token.isEmpty()) {
            log.info( "token为空, 请求被拦截" );
//            return false;
            throw new CustomException("token为空, 请求被拦截", 302);
        }

        Claims claims = JwtUtils.verifyJwt(token);
        //获取用户ID
        if (claims == null) {
            log.warn( "token无效，请求被拦截" );
//            return false;
            throw new CustomException("token无效, 请求被拦截", 302);
        } else {
            // 再和 redis 中的对比
            // 1. 先拿到用户 id
            String userId = JwtUtils.getUserIdByToken(token);
            // 2. 拿到用户类型
            String userType = JwtUtils.getUserTypeByToken(token);
            // 3. 合成密钥
            String key = userType + "-" + userId;
            log.info(key);
            // 5. 从 redis 中拿到 token
            String redisToken = RedisUtils.getJwtTokenFromRedis(key);
            log.info(redisToken);
            // 3. 判断
           if (token.equals(redisToken)) {
               return true;
           }
           throw new CustomException("token无效, 请求被拦截", 302);
        }
    }

    /**
     * post 请求触发的函数
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        long startTime = (Long) request.getAttribute("requestStartTime");
        log.info("------------- LoginInterceptor 结束 耗时：{} ms -------------", System.currentTimeMillis() - startTime);
    }

    /**
     * 拦截之后触发的函数
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        // UserThreadLocal.clear();
        log.info("LogInterceptor 结束");
    }

}
